package com.cn.dao;

import com.cn.BaseDao.BaseDao;
import com.cn.daoIntface.NewsDaoIntface;
import com.cn.entity.NewsEntity;
import com.cn.utilOne.Expression;
import com.cn.utilOne.PageBean;
import com.cn.utilOne.PageConstants;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

public class NewsDao extends BaseDao implements NewsDaoIntface {


    @Override
    public List<NewsEntity> queryAll() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
        String sql = "select * from news where 1=1";
        return this.executeQuery(sql, NewsEntity.class);
    }

    @Override
    public PageBean<NewsEntity> findByCriteria(List<Expression> expressionList, int pc) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
        int ps = PageConstants.NEWS_PAGE_SIZE;
        StringBuilder whereSql = new StringBuilder(" where 1=1");
        List<Object> list = new ArrayList<>();
        Number cont = this.cont(whereSql.toString());
        int tr = cont.intValue();
        String sql = "select * from news" + whereSql + " LIMIT ?,?";
        List<NewsEntity> list1 = this.executeQuery(sql, NewsEntity.class, (pc - 1) * ps, ps);
        PageBean<NewsEntity> pageBean = new PageBean<>();
        pageBean.setBeanList(list1);
        pageBean.setPs(ps);
        pageBean.setTr(tr);
        pageBean.setPc(pc);

        return pageBean;
    }

    @Override
    public NewsEntity queryById(NewsEntity newsEntity) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
        String sql = "select * from news where news_id=? LIMIT 1";
        return (NewsEntity) this.executeQueryOne(sql, NewsEntity.class, newsEntity.getNews_id());
    }

    @Override
    public int addNews(NewsEntity newsEntity) throws SQLException, ClassNotFoundException {
        //产生日期形式的long 型
        Long millisecond = Instant.now().toEpochMilli();
        //产生随机数
        String random = "" + (int) ((Math.random() * 9 + 1) * 1000);
        //拼接成 ID 值
        String id = millisecond + random;
        //创建SQL 语句
        String sql = "insert into news(news_id,title,content,date_in) values(?,?,?,now())";
        //执行添加方法
        return this.executeUpdate(sql, id, newsEntity.getTitle(), newsEntity.getContent());
    }

    @Override
    public int cont(String wheresql) {
        String sql = "select COUNT(*) from news" + wheresql;
        return this.selectCount(sql);
    }

    @Override
    public List<NewsEntity> findAll(int pc, int ps) {
        return null;
    }

    @Override
    public int updateNewsById(NewsEntity newsEntity) {
        return 0;
    }

    @Override
    public Object tableToClass(ResultSet rs) throws Exception {
        return null;
    }
}
